// components/common/calendar-swiper/index.js
import dayjs from 'dayjs';
import componentBehavior from '../../../behaviors/component';
import { COMPONENT_OPTIONS, WEEK_ZH } from'../../../constants/common';

// 获取区间
const getTimeRange = () => {
    const ranges = [];
    for (let i = 0; i < 3; i ++) {
        const weeks = [];
        for (let j = 0; j < 7; j ++) {
            const begin = dayjs().subtract(1, 'week').add(i, 'week').startOf('week').add(j + 1, 'day').valueOf();
            weeks.push({
                begin: dayjs(begin).startOf('day').valueOf(),
                end: dayjs(begin).endOf('day').valueOf(),
                dayStr: `${dayjs(begin).format('DD')}`,
                weekStr: `周${WEEK_ZH[j + 1]}`,
                dateStr: `${dayjs(begin).format('YYYY年MM月')}`,
            });
        };
        ranges.push(weeks);
    }
    return ranges;
};

Component({
    behaviors: [componentBehavior],
    options: {
        ...COMPONENT_OPTIONS,
    },
    properties: {
        currentDate: {
            type: Number,
            value: dayjs().startOf('day').valueOf(),
        },
    },
    data: {
        rangeList: [],
        currentDateStr: '',
        currentIdx: 1,
        currentDateIdx: 1,
    },
    lifetimes: {
        attached: function () {
            const rangeList = getTimeRange();
            this.setData({ rangeList }, () => {
                const { currentDate, currentIdx } = this.data;
                const currentDateIdx = rangeList[currentIdx].findIndex(i => i.begin === currentDate);
                this.setData({
                    currentDateIdx,
                    currentDateStr: `${dayjs(currentDate).format('YYYY年MM月')}`
                });
            });
        },
    },
    methods: {
        handleSwiper(e) {
            const { rangeList, currentDateIdx } = this.data;
            const { current: currentIdx } = e.detail;
            const date = rangeList[currentIdx][currentDateIdx];
            this.setData({
                currentIdx,
                currentDateStr: date.dateStr,
            });
            this.triggerEvent('change', date);
        },
        handleSelect(e) {
            const { date, index } = e.currentTarget ? e.currentTarget.dataset : e;
            this.setData({
                currentDateIdx: index,
                currentDateStr: date.dateStr,
            });
            this.triggerEvent('change', date);
        },
    }
})

